package com.efivestar.idm.api.service.lock.protocol.handler;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.efivestar.idm.api.common.Cons;
import com.efivestar.idm.api.domain.EventDomain;
import com.efivestar.idm.api.domain.WeixinJoinDeviceDomain;
import com.efivestar.idm.api.repository.CameraMapper;
import com.efivestar.idm.api.repository.EventMapper;
import com.efivestar.idm.api.repository.WeixinJoinDeviceMapper;
import com.efivestar.idm.api.service.DeviceService;
import com.efivestar.idm.api.service.WeixinService;
import com.efivestar.idm.api.util.ByteUtils;
import com.efivestar.idm.api.util.weixin.WeixinApi;
import com.efivestar.idm.api.util.weixin.bean.TemplateMessage;

import io.netty.buffer.ByteBuf;
import tk.mybatis.mapper.entity.Example;

/**
 * 远程开锁结果反馈.
 */
@Service
public class RemoteOpenDoorReplyProtocolHandler extends AbstractLockProtocolHandler{

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private EventMapper mapper;


    @Autowired
    private DeviceService deviceService;

    @Autowired
    private WeixinService weixinService;


    @Autowired
    private WeixinJoinDeviceMapper weixinJoinDeviceMapper;

    @Autowired
    private CameraMapper cameraMapper;

    @Autowired
    private WeixinApi weixinApi;

    @Value("${weixin.warningTemplateId:jZt8KiYA6wsIkVqNqL12GAfVnzZftFD895bEva0zPLA}")
    private String warningWeixinTemplateId;

    @Value("${service.domain:51ai.cc}")
    private String domain;



    @Override
    protected int getDataLenthWithoutDeviceId() {
        return 1;
    }

    /**
     * @param buf
     * @param lockId
     * @return
     */
    @Override
    public byte[] handleData(ByteBuf buf, String lockId) {
        int length = buf.readableBytes();
//        读取电量字节
        byte replyCoe = buf.readByte();
        //读取imei(设备编号)
        // String lockId = String.valueOf(buf.readCharSequence(length - getDataLenthWithoutDeviceId(), Charset.forName("utf-8")));
        //设置设备的电量和更新时间
        int eventType = getEventType(replyCoe);
        //微信远程开门成功
        if (eventType == Cons.OPEN_DOOR_BY_WEIXIN_REMOTE_EVENT) {
            EventDomain event = EventDomain.builder().deviceId(lockId).eventType(Cons.OPEN_DOOR_EVENT_TYPE).subEventType(eventType).content("").createTime(new Date()).build();
            mapper.insert(event);
            //通知用户设备开门成功
            sendNotification(lockId, event.getId(), eventType);
        }
        return ByteUtils.hexToBytes("00");
    }


    /**
     * 发送通知信息.
     * 如果是劫持，则信息内容为红色， 并且可以查看摄像头.否则就是普通的信息，点击之后可以跳转到事件列表界面.
     * @param deviceId
     * @param eventId 事件id.
     */
    private void sendNotification(String deviceId, Long eventId, int eventType) {
        //发送微信通知.
        String now = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        List<WeixinJoinDeviceDomain> weixinJoinDeviceDomains = weixinJoinDeviceMapper.selectByExample(generateUserJoinDeviceExample(deviceId));
        for (WeixinJoinDeviceDomain weixinJoinDeviceDomain : weixinJoinDeviceDomains) {
            String toUser = weixinJoinDeviceDomain.getOpenId();
            Map map = new HashMap<>();
            map.put("first", TemplateMessage.builder().value("微信远程开锁通知").color("#74F192").build());
            map.put("keyword1", TemplateMessage.builder().value("远程开锁，门已开").build());
            map.put("keyword2", TemplateMessage.builder().value(now).build());
            String eventDetail = "http://" + domain + "/deviceEvent?eventId=" + eventId;
            boolean result = weixinApi.sendTemplateMessage(toUser, warningWeixinTemplateId, eventDetail,
                    map, null);
            logger.info("开门推送，智能锁id:{}, toUser:{}, 结果： {}", new Object[]{deviceId, toUser, result});
        }
    }


    private Example generateUserJoinDeviceExample(String deviceId) {
        Example example = new Example(WeixinJoinDeviceDomain.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(deviceId)){
            criteria.andEqualTo("deviceId", deviceId);
        }
        return example;
    }



    /**
     * 获取开门的子事件类型.
     * @param eventTypeBt
     * @return
     */
    private int getEventType(byte eventTypeBt) {
        String eventType = ByteUtils.bytes2hex(eventTypeBt);
        switch (eventType) {
            case "10":
                return Cons.OPEN_DOOR_BY_WEIXIN_REMOTE_EVENT;
        }
        return 0;
    }


    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        System.arraycopy(src, begin, bs, 0, count);
        return bs;
    }

    @Override
    public String udpHead(){
        return Cons.UDP_HEAD_EF02;
    }

    @Override
    public String udpCommand(){
        return Cons.UDP_COMMAND_REMOTE_OPEN_DOOR_REPLY;
    }


}






